<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="search-list mb-10">
        <div style="display: flex;align-items: center;margin-right: 10px">
          <div>
            <component
                v-bind:is="item.propertyType"
                :property.sync="item"
                v-for="(item, index) in getPower"
                :key="index"
                @updateVal="updateVal"
            ></component>
          </div>
          <el-date-picker
              v-model="timeData"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              size="small"
              class="mr-10"
              :picker-options="pickerOptions1">
          </el-date-picker>
          <el-button type="primary" size="small" @click="searchFn('search')" class="ml-10"><i
              class="el-icon-search"></i>搜索
          </el-button>
          <el-button size="small" @click="searchFn('refresh')"><i class="el-icon-refresh"></i>重置刷新</el-button>
        </div>
      </div>
      <!--本体列表，数据 -->
      <el-table
          ref="multipleTable"
          :data="arryList"
          :stripe="tableStripe"
          :border="tableBorder"
          tooltip-effect="dark"
          header-cell-class-name="table-text-c"
          cell-class-name="table-text-c">
        <el-table-column
            align="center"
            prop="id"
            label="ID"
            width="60"/>
        <el-table-column
            align="center"
            label="录制内容"
            prop="video"/>
        <!--        <el-table-column-->
        <!--            align="center"-->
        <!--            label="采集备注" />-->
        <el-table-column
            align="center"
            prop="create_time"
            label="录制时间"
            width="170">
        </el-table-column>
        <el-table-column
            align="center"
            label="录制人">
          <template slot-scope="scope">
            {{scope.row.user?scope.row.user.realname: ''}}
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            prop="create_time"
            label="操作"
            width="190">
          <template slot-scope="scope">
<!--            <el-button size="mini" @click="downs(scope.row)" icon="el-icon-download">下载</el-button>-->
            <el-button size="mini" @click="videoSrc=scope.row.videoPath,videoVisible=true" icon="el-icon-video-play">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            :page-size="page.pagesize"
            :current-page="page.pageindex"
            layout="total, prev, pager, next"
            :total="page.total"
            @current-change="handleSizeChange"></el-pagination>
      </el-col>
      <div class="height40"></div>
      <addTrainingUser :visible.sync="addTrainVisible" @InitFn="InitFn" :trainningId="trainningId"></addTrainingUser>
      <!--      <iframe src="http://192.168.0.172/video/record/192.168.0.135_record_2022-08-30 02:58:20.mp4" frameborder="0"></iframe>-->
<!--      <video-player class="video-player vjs-custom-skin"-->
<!--                    ref="videoPlayer"-->
<!--                    :playsinline="true"-->
<!--                    :options="playerOptions">-->
<!--      </video-player>-->
      <showVideo :visible.sync="videoVisible" :videoSrc="videoSrc"></showVideo>
    </div>
  </div>
</template>

<script>
import {pagination} from '@/utils/util.js'
import {patrolIndex} from '@/api/admin/cameraVideo'
import showVideo from "./showVideo";
import {mapGetters} from "vuex";
// import {videoPlayer} from 'vue-video-player'
// import 'video.js/dist/video-js.css'
export default {
  components: {showVideo},
  computed: {
    ...mapGetters(['configData']),
  },
  data() {
    return {
      videoSrc: '',
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4", // 类型
          src: '' // url地址
        }],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      },
      timeData: '',
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      arryList: [], // 数据列表
      // 页数
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      addTrainVisible: false,
      trainningId: 0,
      searchBox: {
        class_id: '',
        section_id: '',
        start_time: '',
        end_time: '',
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now() //  - 8.64e7
        }
      },
      getPower: {
        'section_id': {
          name: 'section_id', // key名称
          default: '', // 默认值
          propertyType: "Select", // 组件名称
          placeholder: '年段', // 默认值
          valueText: '', // 值
          leve: 2,
          api: this.api.user_sectionindex, // 下拉框的请求接口
          keyName: 'section_name',// 调用的字段
          child: [
            {
              name: 'class_id',
              default: '',
              propertyType: "",
              placeholder: '班级',
              valueText: '',
              api: this.api.user_classesindex,
              keyName: 'class_name',
            }
          ]
        }
      },
      treeList: [],
      treeChildList: [],
      videoVisible: false
    }
  },
  watch: {},
  created() {
    this.InitFn()
  },
  methods: {
    downs(item) {
      // let alink = document.createElement("a");
      // // alink.href = openBASE_URL('http')+url;
      // alink.download = `巡班记录_${item.video}`; // 图片名
      // alink.href = `${this.configData.video_url}${item.video}`;
      // alink.click();
      window.open(`${this.configData.video_url}${item.video}`)
      // 将视频文件转为前端可下载的
      // this.getVideoArrayBuffer(`${this.configData.video_url}${item.video}`)
    },
    getVideoArrayBuffer(url, name) {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url, true)
      xhr.responseType = 'arraybuffer' // 返回类型blob
      xhr.onload = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
          const blob = this.response
          console.log(blob)
          // 转换一个blob链接
          // 注: URL.createObjectURL() 静态方法会创建一个 DOMString(DOMString 是一个UTF-16字符串)，
          // 其中包含一个表示参数中给出的对象的URL。这个URL的生命周期和创建它的窗口中的document绑定
          const downLoadUrl = window.URL.createObjectURL(new Blob([blob], {
            type: 'video/mp4'
          }))
          // 视频的type是video/mp4，图片是image/jpeg
          // 01.创建a标签
          const a = document.createElement('a')
          // 02.给a标签的属性download设定名称
          a.download = name
          // 03.设置下载的文件名
          a.href = downLoadUrl
          // 04.对a标签做一个隐藏处理
          a.style.display = 'none'
          // 05.向文档中添加a标签
          document.body.appendChild(a)
          // 06.启动点击事件
          a.click()
          // 07.下载完毕删除此标签
          a.remove()
        }
      }
      xhr.send()
    },
    // 初始化
    async InitFn() {
      let option_ = JSON.parse(JSON.stringify(this.searchBox))
      option_.p = this.page.pageindex
      console.log('timeData:', this.timeData)
      patrolIndex(option_).then(res => {
        console.log('res首页数据:', res)
        // encodeURIComponent('张三')
        // decodeURIComponent(this.$route.query.name)
        for(let item of res.list.data){
          let path_ = ''
          if(item.video.indexOf('/record/')!==-1){
            path_ = item.video.split('/record/')
            path_[1] = encodeURIComponent(path_[1])
          }
          item.videoPath = path_.join('/record/')
        }
        this.arryList = res.list.data;
        this.page.total = res.list.total;
      })
    },
    searchFn(option) {
      if (option === 'refresh') {
        let newGetPower = JSON.parse(JSON.stringify(this.getPower))
        newGetPower['section_id'].valueText = '';
        newGetPower['section_id'].child[0].valueText = '';
        this.getPower = newGetPower;
        this.searchBox.class_id = '';
        this.searchBox.section_id = '';
        this.searchBox.start_time = ''
        this.searchBox.end_time = ''
        this.timeData = []
      } else {
        if (this.timeData && this.timeData.length) {
          this.searchBox.start_time = this.timeData[0]
          this.searchBox.end_time = this.timeData[1]
        }
      }
      this.page.pageindex = 1;
      this.InitFn()
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      this.InitFn()
    },
    deletefn(id) {
      this.$confirm('确认永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detelCalss(id)
      }).catch(() => {
      })
    },
    async detelCalss(id) {
      let data = await this.$post(this.api.classActive.training.delete, {id: id})
      if (!data.code) {
        this.$message.success(data.msg)
        this.InitFn()
      }
    },
    // 更新值
    updateVal(option) {
      // console.log('变更数据收到的数据内容：', option)
      if (option.input) {
        this.searchBox[option['input'].name] = option['input'].valueText
      } else if (option.select) {
        for (let i in option.select) {
          if (option.select[i].name) {
            this.searchBox[option.select[i].name] = option.select[i].valueText
          } else {
            this.searchBox[option.select[i - 1].name] = option.select[i].valueText ? option.select[i].valueText : option.select[i - 1].valueText
          }
        }
      }
    },
  },
  mounted() {
  },
}
</script>
<style>
</style>

